package org.aspectsense.middleware;

import java.util.logging.Logger;

import org.aspectsense.middleware.gui.ControlPanel;
import org.aspectsense.middleware.monitor.DefaultBundleListener;
import org.aspectsense.middleware.monitor.DefaultServiceListener;
import org.aspectsense.middleware.monitor.EventsManager;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

/**
 * Activates the middleware bundle
 * @author Nearchos Paspallis
 * @author Costas Kakousis
 *
 */
public class AspectSense implements BundleActivator {

	private DefaultBundleListener bundleListener;
	private DefaultServiceListener serviceListener;
	private EventsManager eventsManager;
	private static final Logger logger = Logger.getLogger(org.aspectsense.middleware.AspectSense.class.getCanonicalName());

	public AspectSense (){
		super();
		
	}

	/**
	 * When the middleware bundle starts we set up Listeners for monitoring 
	 * OSGi bundle and service events
	 */
	public void start(BundleContext context) throws Exception {
	
		this.bundleListener = new DefaultBundleListener();
		this.serviceListener = new DefaultServiceListener();
		this.eventsManager = new EventsManager();
		Repository.bundleContext = context;
		if((bundleListener!=null)&&(serviceListener!=null)&&(eventsManager!=null))
			logger.info("AspectSense Middleware is OK");
		else
		{
			logger.info("Bundle and Service Listeners failed to start! /n AspectSense is closing down");
			System.exit(0);
		}
		
		//Set the listeners and start the events manager thread
		context.addBundleListener(this.bundleListener);
		context.addServiceListener(this.serviceListener);
		eventsManager.activate();
		new ControlPanel();
		
	}
	
	/**
	 * Stop the middleware bundle and remove the listeners
	 */
	public void stop(BundleContext context) throws Exception {
		logger.info("AspectSense Middleware is OFF");
		 context.removeBundleListener(bundleListener);
	     context.removeServiceListener(serviceListener);
	 	eventsManager.deactivate();
	 
	}

}
